package com.skyworthclub.competition.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.skyworthclub.competition.beans.Role;
import com.skyworthclub.competition.beans.User;
import com.skyworthclub.competition.mapper.RoleMapper;
import com.skyworthclub.competition.mapper.UserMapper;
import com.skyworthclub.competition.service.RoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.skyworthclub.competition.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author li
 * @since 2019-06-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMapper roleMapper;
    private final UserService userService;

    @Autowired
    public RoleServiceImpl(RoleMapper roleMapper, UserService userService) {
        this.roleMapper = roleMapper;
        this.userService = userService;
    }

    @Override
    public List<Role> getRolesByUserId(Integer userId) {
        return roleMapper.getRolesByUserId(userId);
    }

    @Override
    public List<Role> getRolesByUserName(String username) {
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        User user = userService.selectOne(wrapper);
        if (user == null) {
            return Collections.emptyList();
        }
        return roleMapper.getRolesByUserId(user.getId());
    }

    @Override
    public boolean grantAdminRole(Integer userId) {
        EntityWrapper<Role> wrapper = new EntityWrapper<>();
        wrapper.eq("role_name", "admin");
        Role role = super.selectOne(wrapper);
        return roleMapper.grantRole(userId, role.getRoleId());
    }
}
